package com.gton.person.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: PersonalDesign
 * @description: 字符编码过滤器
 * @author: GuoTong
 * @create: 2020-11-30 10:16
 **/
//字符编码过滤器
@WebFilter(urlPatterns = "/*", filterName = "CharacterEncodingFilter")
public class CharacterEncodingFilter implements Filter {
    /*过滤器初始化该做什么。。。*/
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /*JSP&Servlet模型的三大组件之一：filter过滤器：这里用作全局字符编码设置为UTF-8*/
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //拿到request对象和response对象，设置请求编码格式和响应编码格式，最后一定要放行
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        filterChain.doFilter(request, response);
    }

    /*过滤器销毁的时候做什么。。*/
    @Override
    public void destroy() {
    }
}
